User = require('../models/user')


#注册页面路由
exports.showSignup = (req, res)->
  res.render 'signup', {
    title: '注册页面'
  }

#登陆页面路由
exports.showSignin = (req, res)->
  res.render 'signin', {
    title: '登陆页面'
  }

#注册机制
exports.signup = (req, res)->
  _user = req.body.user
  # console.log JSON.stringify(_user)
  User.findOne {name: _user.name}, (err, user)->
    console.log err if err
    if user.length is 0
      return res.redirect('/signin')
    else
      user = new User(_user)
      user.save (err, user)->
        console.log err if err
        res.redirect('/')

#登陆机制
exports.signin = (req, res)->
  _user = req.body.user
  name = _user.name
  password = _user.password

  User.findOne {name: name}, (err, user)->
    console.log err if err

    return res.redirect('/signup') if !user
    user.comparePassword password, (err, isMatch)->
      console.log err if err
      if isMatch
        #登陆上了直接存储数据到session
        req.session.user = user

        return res.redirect('/')
      else
        return res.redirect('/signin')
        console.log("Password is not matched")

# logout
exports.logout =  (req, res)->
  delete req.session.user
  # delete app.locals.user
  res.redirect('/')

# userlist page
exports.list = (req, res)->
  User.fetch (err,users)->
    console.log err if err
    res.render 'userlist', {
      title: '用户列表页',
      users: users
    }

# midware for user
exports.signinRequired = (req, res, next)->
  user = req.session.user
  if !user
    return res.redirect('/signin')
  next()

# midware for user
exports.adminRequired = (req, res, next)->
  user = req.session.user
  if user.role <= 10
    return res.redirect('/signin')
  next()
